import psutil
import get_hyperlink_from_md
import get_hyperlink_from_readme
from deal_with_excel import get_urls_from_excel, result_write_to_excel
from deal_with_url import classify_url, check_md_url, check_http_url
from src.utils.global_variable import logging, Var
# pyppeteer浏览器窗口数据
WINDOW_WIDTH, WINDOW_HEIGHT = 1920, 1080


def kill_chromium_process(process_name):
    # 遍历所有进程
    for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
        if not proc.info['cmdline']:
            continue
        if process_name in proc.info['cmdline'][0]:
            try:
                proc.terminate()  # 尝试正常终止进程
                proc.wait(timeout=3)  # 等待3秒看进程是否终止
                if proc.is_running():
                    proc.kill()  # 如果进程仍在运行，则强制终止
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass  # 忽略这些异常

    logging.info(f"Processes named '{process_name}' have been terminated.")


def main(queue, md_file_path, test_mode):
    var = Var()
    logging.info(f'Start getting hyperlinks')
    queue.put(f'Start getting hyperlinks')

    var.excel_path = get_hyperlink_from_md.main(md_file_path, queue)  # 获取md文件中的超链接
    all_urls = get_urls_from_excel(var.excel_path)  # 获取所有待检测的超链接
    http_urls, md_urls = classify_url(all_urls)  # 将超链接分类未https链接和md链接

    # 对链接进行去重
    unique_http_urls = list(set(http_urls))
    unique_md_urls = list(set(md_urls))

    # 链接检测
    check_md_url(unique_md_urls, queue)  # 检查MD超链接

    # 通过异步方式检查https链接
    check_http_url(unique_http_urls, test_mode, queue)
    queue.put(100)

    # 将结果写入导表格中
    result_write_to_excel(var.excel_path, var.result_dict)

    # 杀掉未结束的进程
    kill_chromium_process("chromium")
    queue.put(f'The link check is completed successfully. For details, see.{var.excel_path}')


def readme_main(queue, dir_path, test_mode):
    var = Var()
    logging.info(f'Start getting hyperlinks')
    queue.put(f'Start getting hyperlinks')

    var.excel_path = get_hyperlink_from_readme.main(dir_path, queue)  # 获取readme文件中的超链接
    all_urls = get_urls_from_excel(var.excel_path)  # 获取所有待检测的超链接
    http_urls, md_urls = classify_url(all_urls)  # 将超链接分类未https链接和md链接

    # 对链接进行去重
    unique_http_urls = list(set(http_urls))

    # 通过异步方式检查https链接
    check_http_url(unique_http_urls, test_mode, queue)
    queue.put(100)

    # 将结果写入导表格中
    result_write_to_excel(var.excel_path, var.result_dict)

    # 杀掉未结束的进程
    kill_chromium_process("chromium")
    queue.put(f'The link check is completed successfully. For details, see.{var.excel_path}')



if __name__ == '__main__':
    pass
